package com.ccc.controller;


import com.ccc.entity.StuLeave;
import com.ccc.mapper.StuLeaveMapper;
import com.ccc.utils.JwtUtil;
import com.ccc.utils.ResponseResult;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author ccc
 * @since 2022-01-02
 */
@Controller
public class StuLeaveController {

    @Autowired
    StuLeaveMapper stuLeaveMapper;

    /**
     * 教师请求请假表，返回的是所有学生的请假信息
     *
     * @return
     */
    @GetMapping("/teacher/leavelist")
    @PreAuthorize("hasAuthority('teacher')")
    @ResponseBody
    public ResponseResult leaveList() {
        return new ResponseResult(200, "success", stuLeaveMapper.leaveList());
    }

    /**
     * 学生请求请假表，返回的是该学生的请假信息
     *
     * @param request
     * @return
     */
    @GetMapping("/stu/leavelist")
    @PreAuthorize("hasAuthority('student')")
    @ResponseBody
    public ResponseResult stuLeaveList(HttpServletRequest request) {
        String token = request.getHeader("token");
        String username;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            username = claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseResult(400, "token Error!");
        }

        return new ResponseResult(200, "success", stuLeaveMapper.leaveListById(username));
    }

    /**
     * 学生添加请假信息
     *
     * @param stuLeave
     * @param request
     * @return
     */
    @PostMapping("/stu/addLeave")
    @PreAuthorize("hasAuthority('student')")
    @ResponseBody
    public ResponseResult addLeave(@RequestBody StuLeave stuLeave, HttpServletRequest request) {
        String token = request.getHeader("token");
        String username;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            username = claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseResult(400, "token Error!");
        }
        stuLeaveMapper.addLeave(username, stuLeave.getReason(), stuLeave.getDateFrom(), stuLeave.getDateTo());
        return new ResponseResult(200, "success");
    }

}
